#include "headfiles.h"

using namespace std;

NODE *createLinkedListTmp(const char *file_name) {
    fstream fs;
    NODE *head = NULL;
    fs.open(file_name, iostream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return NULL;
    }

    string str;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }

        int val = atoi(str.c_str());
        NODE *tmp = new NODE;
        tmp->val = val;
        tmp->next = head;
        head = tmp;
    }
    fs.close();

    return head;
}

void printLinkedList(NODE *head) {
    NODE *n1;
    n1 = head;
    while (n1) {
        cout << n1->val << "\t";
        n1 = n1->next;
    }
    cout << endl;
}

NODE *addTwoNumbers(NODE *l1, NODE *l2) {
    int carry = 0;
    NODE *n1, *n2, *head, *tail, *tmp;
    n1 = l1;
    n2 = l2;
    head = NULL;
    while (n1 && n2) {
        NODE *tmp = new NODE(0);
        tmp->val = n1->val + n2->val + carry;
        tmp->next = NULL;
        carry = 0;
        if (tmp->val >= 10) {
            tmp->val -= 10;
            carry = 1;
        }
        
        if (head == NULL) {
            head = tail = tmp;
        }
        else {
            tail->next = tmp;
            tail = tmp;
        }
        
        n1 = n1->next;
        n2 = n2->next;
    }
    
    // Remaining nodes exist in l1
    while (n1) {
        NODE *tmp = new NODE(0);
        tmp->val = n1->val + carry;
        tmp->next = NULL;
        carry = 0;
        if (tmp->val >= 10) {
            tmp->val -= 10;
            carry = 1;
        }
        
        if (head == NULL) {
            tail = head = tmp;
        }
        else {
            tail->next = tmp;
            tail = tmp;
        }
        n1 = n1->next;
    }

    while (n2) {
        NODE *tmp = new NODE(0);
        tmp->val = n2->val + carry;
        tmp->next = NULL;
        carry = 0;
        if (tmp->val >= 10) {
            tmp->val -= 10;
            carry = 1;
        }
        
        if (head == NULL) {
            tail = head = tmp;
        }
        else {
            tail->next = tmp;
            tail = tmp;
        }
        n2 = n2->next;
    }

    if (carry) {
        NODE *tmp = new NODE(0);
        tmp->val = carry;
        tail->next = tmp;
        tail = tmp;
    }

    return head;
}
